<template>
  <el-dialog v-if="load" :title="title" v-model="visible" align-center width="800px" @close="handleClose" :close-on-click-modal="false">
    <el-form :model="formData" label-width="140px" :rules="rules" inline ref="ruleFormRef" class="formw200" label-position="top">
      <el-form-item label="模板名称" prop="template_name">
        <el-input v-model="formData.template_name" class="w-[320px]" placeholder="模板名称" />
      </el-form-item>
      <!-- 状态 -->
      <el-form-item prop="state">
        <template #label>
          <span style="color: #fff">_</span>
        </template>
        <el-switch v-model="formData.state" :active-value="1" :inactive-value="0" inline-prompt active-text="启用" inactive-text="禁用"></el-switch>
      </el-form-item>
      <el-form-item label="开发人员" prop="developer">
        <el-cascader
          v-model="formData.developer"
          :options="organizationData"
          :props="cascaderProps"
          :show-all-levels="false"
          collapse-tags
          clearable
          filterable
          placeholder="开发人员"
          class="w-[320px]"
        />
      </el-form-item>

      <div class="w-[100%]">
        <el-form-item label="是否展示平台" prop="is_show_platform" class="w-[320px] inline-block">
          <el-radio-group v-model="formData.is_show_platform">
            <el-radio :label="item.value" size="large" v-for="(item, index) in options" :key="index">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否展示品类" prop="is_show_category" class="w-[300px] inline-block">
          <el-radio-group v-model="formData.is_show_category">
            <el-radio :label="item.value" size="large" v-for="(item, index) in options" :key="index">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <el-form-item label="SPU添加时间（全新品品类）" prop="spu_brand_new.max" v-if="formData.is_show_category == 1" class="w-[320px]">
        <NumberRange :value="formData.spu_brand_new" suffix="月" @input="updateNumberRange('spu_brand_new', $event)" />
      </el-form-item>

      <el-form-item label="SPU添加时间（老品新组合）" prop="spu_renovation.max" v-if="formData.is_show_category == 1" class="w-[320px]">
        <NumberRange :value="formData.spu_renovation" suffix="月" @input="updateNumberRange('spu_renovation', $event)" />
      </el-form-item>

      <el-form-item label="新品时间范围" prop="new_product.max" class="w-[320px]">
        <NumberRange :value="formData.new_product" suffix="月" @input="updateNumberRange('new_product', $event)" />
      </el-form-item>

      <el-form-item label="老品时间范围" prop="old_product.max" class="w-[320px]">
        <NumberRange :value="formData.old_product" suffix="月" @input="updateNumberRange('old_product', $event)" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { nextTick, reactive, toRefs } from "vue"
import { commissionSettingStore, commissionSettingUpdate, createSetting, updateSetting } from "../api"
import { ElMessage, notificationEmits } from "element-plus"
import NumberRange from "@/components/NumberRange/index.vue"
const ruleFormRef = ref()
const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
// 声明接收参数
const props = defineProps({
  title: {
    type: String,
    default: "新增",
  },
  ruleTypeOption: {
    type: Object,
    default: [],
  },
  formula: {
    type: Array,
    default: [],
  },
  vat_type: {
    type: Array,
    default: [],
  },
})

const updateNumberRange = (field, val) => {
  console.log(val)
  if (!val.min) {
    val.min = 0
  }
  if (!val.max) {
    val.max = 0
  }
  if (val.min == 0 && val.max == 0) {
    val.min = ""
    val.max = ""
  }
  formData.value[field] = val
}

const data = reactive({
  isType: false,
  formData: {
    is_show_platform: 1,
    is_show_category: 1,
    new_product: {
      min: "", // new_product_start
      max: "", // new_product_end
    },
    old_product: {
      min: "", // old_product_start
      max: "", // old_product_end
    },
    spu_brand_new: {
      min: "", // spu_brand_new_start
      max: "", // spu_brand_new_end
    },
    spu_renovation: {
      min: "", // spu_renovation_start
      max: "", // spu_renovation_end
    },
    state: 1,
  },
})
const { formData, isType, platformList, siteList, shopList } = toRefs(data)
const rules = reactive({
  template_name: [{ required: true, message: "不能为空", trigger: "blur" }],
  developer: [{ required: true, message: "请选择", trigger: "change" }],
  "new_product.max": [{ required: true, message: "不能为空", trigger: "blur" }],
  "old_product.max": [{ required: true, message: "不能为空", trigger: "blur" }],
  "spu_brand_new.max": [{ required: true, message: "不能为空", trigger: "blur" }],
  "spu_renovation.max": [{ required: true, message: "不能为空", trigger: "blur" }],
})

const { title, ruleTypeOption, formula, vat_type } = toRefs(props)
const emit = defineEmits(["close", "confirm"])

import cache from "@/plugins/cache"
import { organizationList } from "@/api/public"
const organizationData = ref([])
const organizationListF = async () => {
  let personnelOptions = cache.session.getJSON("personnel") || ""
  if (personnelOptions) {
    organizationData.value = personnelOptions
  } else {
    organizationList().then((res) => {
      organizationData.value = res.data
      cache.session.setJSON("personnel", res.data)
    })
  }
}
const cascaderProps = ref({
  emitPath: false,
  multiple: true,
  label: "name",
  value: "id",
  children: "sub",
})

// 打开弹窗
const open = (row = {}) => {
  // console.log(112233)
  // console.log(row)
  if (!load.value) {
    load.value = true
  }
  if (row.id) {
    notificationEmits
    nextTick(() => {
      formData.value = { ...formData.value, ...row }
      formData.value.new_product = { min: row.new_product_start, max: row.new_product_end }
      formData.value.old_product = { min: row.old_product_start, max: row.old_product_end }
      formData.value.spu_brand_new = { min: row.spu_brand_new_start, max: row.spu_brand_new_end }
      formData.value.spu_renovation = { min: row.spu_renovation_start, max: row.spu_renovation_end }
      console.log(formData.value)
    })

    isType.value = true
    visible.value = true
  } else {
    isType.value = false
    visible.value = true
  }
}
const options = ref([
  { label: "展示", value: 1 },
  { label: "不展示", value: 0 },
])
// 关闭弹窗
const close = () => {
  formData.value = {
    is_show_platform: 1,
    is_show_category: 1,
    new_product: {
      min: "", // new_product_start
      max: "", // new_product_end
    },
    old_product: {
      min: "", // old_product_start
      max: "", // old_product_end
    },
    spu_brand_new: {
      min: "", // spu_brand_new_start
      max: "", // spu_brand_new_end
    },
    spu_renovation: {
      min: "", // spu_renovation_start
      max: "", // spu_renovation_end
    },
    state: 1,
  }
  ruleFormRef.value.resetFields()
  visible.value = false
}

const handleClose = () => {
  close()
  emit("close")
}
// 提交
const submit = () => {
  let { validate } = ruleFormRef.value
  validate((valid) => {
    if (valid) {
      loadings.submit = true
      let params = {
        template_name: formData.value.template_name,
        developer: formData.value.developer,
        is_show_platform: formData.value.is_show_platform,
        is_show_category: formData.value.is_show_category,

        new_product_start: formData.value.new_product.min || 0,
        new_product_end: formData.value.new_product.max || 0,
        old_product_start: formData.value.old_product.min || 0,
        old_product_end: formData.value.old_product.max || 0,
        spu_brand_new_start: formData.value.spu_brand_new.min || 0,
        spu_brand_new_end: formData.value.spu_brand_new.max || 0,
        spu_renovation_start: formData.value.spu_renovation.min || 0,
        spu_renovation_end: formData.value.spu_renovation.max || 0,
        state: formData.value.state,
      }



      if (isType.value) {
        params.id = formData.value.id
        commissionSettingUpdate(params)
          .then((res) => {
            ElMessage({ message: "保存成功", type: "success" })
            emit("confirm")
            close()
          })
          .finally(() => {
            loadings.submit = false
          })
      } else {
        commissionSettingStore(params)
          .then((res) => {
            ElMessage({ message: "保存成功", type: "success" })
            emit("confirm")
            close()
          })
          .finally(() => {
            loadings.submit = false
          })
      }
    }
  })
}
defineExpose({ open })
onMounted(() => {
  organizationListF()
})
</script>
<style lang="scss" scoped></style>
